from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from oauth.exceptions import OAuthQQAPIError
from oauth.models import OAuthQQUser
from oauth.serilizers import OAuthQQUserSerializer

from . import utils


class QQAuthURLView(APIView):
    """
    获取QQ登录的url
    """

    def get(self, request):
        """
        获取QQ登录的网址
        :param request:
        :return:
        """
        next = request.query_params.get('next')
        oauth = utils.OAuthQQ(state=next)
        login_url = oauth.get_qq_login_url()

        return Response({'login_url': login_url})


class QQAuthUserView(GenericAPIView):
    """
    获取登录QQ用户openid
    """

    def get(self, request):
        """
        获取qq登录用户的数据
        :param request:
        :return:
        """
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        oauth = utils.OAuthQQ()

        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_openid(access_token)
        except OAuthQQAPIError:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 判断用户是否存在
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            # 用户不存在
            token = oauth.generate_bind_user_access_token(openid)
            return Response({'access_token': token})

        else:
            # 用户存在
            user = qq_user.user

            # 手动签发JWT
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            return response

    serializer_class = OAuthQQUserSerializer

    def post(self, request):
        """
        保存QQ用户绑定的数据
        :param request:
        :return:
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 手动签发JWT
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })
        return response
